const db = require('../db/index.js')
const util = require('util')
const query = util.promisify(db.query).bind(db)

function getTree(results, permissionId) {
    // console.log(permissionId)
    //生成第一层
    let arr = [];
    for (var i = 0; i < results.length; i++) {

        if (results[i]['ps_level'] == 0) {

            results[i] = {
                "id": results[i]['ps_id'],
                "authName": results[i]['ps_name'],
                "level": results[i]['ps_level'],
                "pid": results[i]['ps_pid'],
                "path": results[i]['ps_api_path'],
                "children": []
            }
            if (permissionId.length !== 0 && permissionId.indexOf(results[i]['id'] + '') == -1) {
                continue;
            }
            arr.push(results[i])
        }
    }



    //生成二层
    for (var i = 0; i < results.length; i++) {
        if (results[i]['ps_level'] == 1) {
            for (var j = 0; j < arr.length; j++) {
                if (results[i]['ps_pid'] == arr[j].id) {
                    results[i] = {
                        "id": results[i]['ps_id'],
                        "authName": results[i]['ps_name'],
                        "level": results[i]['ps_level'],
                        "pid": results[i]['ps_pid'],
                        "path": results[i]['ps_api_path'],
                        "children": []
                    }
                    if (permissionId.length !== 0 && permissionId.indexOf(results[i]['id'] + '') == -1) {
                        continue;
                    }
                    arr[j].children.push(results[i])
                }
            }
        }
    }
    //生成3级
    for (var i = 0; i < results.length; i++) {
        if (results[i]['ps_level'] == 2) {
            for (var j = 0; j < arr.length; j++) {
                for (var c = 0; c < arr[j].children.length; c++) {
                    if (results[i]['ps_pid'] == arr[j].children[c].id) {
                        results[i] = {
                            "id": results[i]['ps_id'],
                            "authName": results[i]['ps_name'],
                            "level": results[i]['ps_level'],
                            "pid": results[i]['ps_pid'],
                            "path": results[i]['ps_api_path'],
                            // "children": []
                        }
                        if (permissionId.length !== 0 && permissionId.indexOf(results[i]['id'] + '') == -1) {
                            continue;
                        }
                        arr[j].children[c].children.push(results[i])
                    }
                }

            }
        }
    }

    return arr

}
exports.getRights = (req, res) => {
    let type = req.params.type
    let sql1 = 'select * from sp_permission a left join sp_permission_api b on (a.ps_id = b.ps_id)';
    var obj = {
        data: {},
        meta: {
            status: '',
            msg: ''
        }
    }

    db.query(sql1, (err, results) => {
        if (err) {
            obj.meta.status = 500;
            obj.meta.msg = '数据库查询错误';
            return res.send(obj);
        } else {
            if (type === 'list') {
                for (var i = 0; i < results.length; i++) {
                    results[i] = {
                        "id": results[i]['ps_id'],
                        "authName": results[i]['ps_name'],
                        "level": results[i]['ps_level'],
                        "pid": results[i]['ps_pid'],
                        "path": results[i]['ps_api_path']
                    }
                }
                obj.data = results;
                obj.meta.status = 200;
                obj.meta.msg = '获取权限列表成功';
                return res.send(obj);
            } else { //tree
                var arr = getTree(results, [])
                obj.data = arr;
                obj.meta.status = 200;
                obj.meta.msg = '获取权限列表成功';
                return res.send(obj);
            }

        }
    })
}


exports.getRoles = (req, res) => {
    let sql1 = 'select * from sp_role'
    let sql2 = 'select * from sp_permission a left join sp_permission_api b on (a.ps_id = b.ps_id)'
    var obj = {
        data: {},
        meta: {
            status: '',
            msg: ''
        }
    }
    db.query(sql1, (err, results) => {
        if (err) {
            obj.meta.status = 500;
            obj.meta.msg = '数据库查询错误';
            return res.send(obj);
        } else {
            db.query(sql2, (err, data) => {
                if (err) {
                    obj.meta.status = 500;
                    obj.meta.msg = '数据库查询错误';
                    return res.send(obj);
                } else {
                    for (var i = 0; i < results.length; i++) {
                        let keyid = results[i]['ps_ids'].split(',')
                        let tree = JSON.parse(JSON.stringify(data))
                        results[i] = {
                            "id": results[i]['role_id'],
                            "roleName": results[i]['role_name'],
                            "roleDesc": results[i]['role_desc'],
                            "children": getTree(tree, keyid)
                        }
                    }
                    obj.meta.status = 200;
                    obj.meta.msg = '角色列表获取成功';
                    obj.data = results;
                    return res.send(obj);
                }
            })




        }
    })

}



exports.setRolesRights = (req, res) => {
    let uid = req.params.roleId;
    let rids = req.body.rids;
    let sql1 = "update sp_role set ? where role_id = ?"
    db.query(sql1, [{ ps_ids: rids }, uid], (err, results) => {
        if (err) {
            obj.meta.status = 500;
            obj.meta.msg = '数据库查询错误';
            return res.send(obj);
        } else {
            console.log(results)
            if (results.affectedRows == 1) {
                obj.meta.status = 200;
                obj.meta.msg = '更新成功';
                obj.data = [];
                return res.send(obj);
            }
        }
    })
    return res.send("ok")
}